<?php
/**
 * Eka Framework 0.3.0
 *
 * @copyright Copyright (c) 2008 Alexey Yu. Chuprina <656b61@gmail.com> (http://php-eka.googlecode.com)
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 *
 * @version $Id$
 */

/**
 * Eka_Mail
 *
 * @package Mail
 */
class Eka_Mail
{
	private $from;
	private $to = array();
	private $subject;
	private $text;

	public function __construct()
	{}

	public function setFrom($email, $name = false)
	{
		$this->from = array(
			'email' => $email,
			'name' => $name
		);
		return $this;
	}

	public function setTo($email, $name = false)
	{
		if (is_array($email)) {
			$emails = $email;
			foreach ($emails as $email => $name) {
				if (is_numeric($email)) {
					$this->setTo($name);
				} else {
					$this->setTo($email, $name);
				}
			}
		} else {
			$this->to[] = array(
				'email' => $email,
				'name' => $name
			);
		}
		return $this;
	}

	public function setSubject($subject)
	{
		$this->subject = $subject;
		return $this;
	}

	public function setText($text)
	{
		$this->text = $text;
		return $this;
	}

	public function send()
	{
		$headers = array();

		$to = array();
		foreach ($this->to as $row) {
			if ($row['name']) {
				$to[] = mb_encode_mimeheader($row['name']) . ' <'.$row['email'].'>';
			} else {
				$to[] = $row['email'];
			}
		}
		$to = join(',', $to);

		if ($this->from) {
			if ($this->from['name']) {
				$headers['From'] = mb_encode_mimeheader($this->from['name']) . ' <'.$this->from['email'].'>';
			} else {
				$headers['From'] = $this->from['email'];
			}
			$f = '-f'.$this->from['email'];
		} else {
			$f = null;
		}

		$headers['Reply-To'] = $headers['From'];
		$headers['Sender'] = $headers['From'];
		$headers['MIME-Version'] = '1.0';
		$headers['Content-Type'] = 'text/plain; charset=utf-8';

		foreach ($headers as $name => &$value) {
			$value = $name . ': ' . $value;
		}

		$result = mb_send_mail($to, $this->subject, $this->text, join("\n", $headers), $f);

		return $result;
	}
}